package com.ymt.bpm.service.platform.config.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ymt.bpm.dao.MDao;
import com.ymt.bpm.dao.Mapper;
import com.ymt.bpm.model.Const.Oplog;
import com.ymt.bpm.service.platform.config.BizDataManagerService;
import com.ymt.bpm.service.platform.log.OpLogService;
import com.ymt.bpm.util.Const;
import com.ymt.bpm.util.DateUtil;
import com.ymt.bpm.util.DhxUtil;
import com.ymt.fmd.model.PBdm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BizDataManagerServiceImpl implements BizDataManagerService {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MDao dao;

    @Autowired
    private OpLogService oplog;

    @Override
    public JSONObject query(String tenantId, String appId, String search, String sort, String order, int offset, int limit, int timezoneOffset) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put(Const.TENANT_ID, tenantId);
        paramMap.put("search", search);
        paramMap.put("appId", appId);
        paramMap.put("sort", sort);
        paramMap.put("order", order);
        PageHelper.offsetPage(offset, limit);
        List<PBdm> list = dao.selectList(Mapper.PBdmMapper, "queryAll", paramMap);
        PageInfo pageInfo = new PageInfo(list);
        JSONObject rtn = new JSONObject();
        JSONArray rows = new JSONArray();
        if (list!=null && list.size()>0) {
            for (PBdm bdm : list) {
                JSONObject node = DhxUtil.toJsonWithDateAli(bdm, Const.LANG_ZH, timezoneOffset);
                node.put("_ITEM_NO", ++offset);
                rows.add(node);
            }
        }
        rtn.put("rows", rows);
        rtn.put("total", pageInfo.getTotal());
        return rtn;
    }

    @Override
    public JSONObject get(String tenantId, String appId, String bdmId, String lang, int timezoneOffset) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put(Const.TENANT_ID, tenantId);
        paramMap.put("bdmId", bdmId);
        PBdm bo = dao.selectOne(Mapper.PBdmMapper, "selectByPrimaryKey", paramMap);
        JSONObject rtn = DhxUtil.toFastJsonWithDate(bo, lang, timezoneOffset);
        return rtn;
    }

    @Override
    public String checkAttr(String tenantId, String appId, String attrName, String value, String bdmId) {
        if (log.isDebugEnabled()) {
            log.debug("checkAttr tenantId="+tenantId);
            log.debug("checkAttr attrName="+attrName);
            log.debug("checkAttr value="+value);
            log.debug("checkAttr bdmId="+bdmId);
        }
        /*if (value!=null && !value.toUpperCase().startsWith("B_")) {
            value = "B_"+value;
        }*/
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("tenantId", tenantId);
        paramMap.put("value", value);
        paramMap.put("bdmId", bdmId);
        int rs = dao.selectOne(Mapper.PBdmMapper, "checkAttr"+ StringUtils.capitalize(attrName), paramMap);
        if (log.isDebugEnabled()) {
            log.debug("checkAttr rs="+rs);
        }
        return rs>0 ? "false" : "true";
    }

    @Override
    public JSONObject save(String tenantId, PBdm bdm, String loginName, String displayName) {
        Long bdmId = bdm.getBdmId();
        if (bdmId==null || bdmId==0L) {
            if (tenantId!=null && org.apache.commons.lang.StringUtils.isNumeric(tenantId)) {
                bdm.setTenantId(Integer.parseInt(tenantId));
            }
            bdm.setCreator(loginName);
            bdm.setCreatorName(displayName);
            bdm.setCreateTime(DateUtil.getGMTDate());
            bdm.setUpdator(loginName);
            bdm.setUpdatorName(displayName);
            bdm.setUpdateTime(DateUtil.getGMTDate());
            dao.insert(Mapper.PBdmMapper, "insert", bdm);

            //记录日志
            oplog.bizlog(tenantId, loginName, displayName, null, Oplog.OP.CREATE, Oplog.CODE.BDM, bdm.getName());
        } else {
            if (tenantId!=null && org.apache.commons.lang.StringUtils.isNumeric(tenantId)) {
                bdm.setTenantId(Integer.parseInt(tenantId));
            }
            bdm.setUpdator(loginName);
            bdm.setUpdatorName(displayName);
            bdm.setUpdateTime(DateUtil.getGMTDate());
            dao.update(Mapper.PBdmMapper, "updateByPrimaryKeySelective", bdm);

            //记录日志
            oplog.bizlog(tenantId, loginName, displayName, null, Oplog.OP.UPDATE, Oplog.CODE.BDM, bdm.getName());
        }
        JSONObject rtn = new JSONObject();
        rtn.put(Const.AJAX_RESULT, true);
        return rtn;
    }

    @Override
    public JSONObject delete(String tenantId, String loginName, String displayName, String appId, String bdmId) {
        JSONObject rtn = new JSONObject();
        int rs = 0;

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put(Const.TENANT_ID, tenantId);
        paramMap.put("bdmId", bdmId);

        //TODO check reference in bpd
        /*List<Map<String, Object>> refList = dao.selectList("POrgPosMapper", "selectPosReferedByOrg", paramMap);
        if (refList!=null && refList.size()>0) {
            StringBuilder names = new StringBuilder();
            for (Map<String, Object> map : refList) {
                if (names.length()>0) {
                    names.append(",");
                }
                names.append(map.get("ORG_NAME"));
            }
            rtn.put("referedForms", names);
            return rtn;
        }*/

        PBdm bdm = dao.selectOne(Mapper.PBdmMapper, "selectByPrimaryKey", Long.parseLong(bdmId));

        rs = dao.delete(Mapper.PBdmMapper, "deleteByPrimaryKey", paramMap);
        rtn.put("result", rs);

        //记录日志
        oplog.bizlog(tenantId, loginName, displayName, null, Oplog.OP.DELETE, Oplog.CODE.BDM, bdm.getName());

        return rtn;
    }

}
